package com.hoppinzq.service;

import com.hoppinzq.bean.Chat;
import com.hoppinzq.bean.ChatMessage;
import com.hoppinzq.dao.ChatMapper;
import com.hoppinzq.dao.ChatMessageMapper;
import com.hoppinzq.service.aop.annotation.ApiMapping;
import com.hoppinzq.service.aop.annotation.ApiServiceMapping;
import com.hoppinzq.service.bean.ApiResponse;
import com.hoppinzq.service.bean.RequestContext;
import com.hoppinzq.service.bean.RequestInfo;
import com.hoppinzq.service.bean.RequestParam;
import okhttp3.*;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ApiServiceMapping(title = "chatGPT管理",description = "chatGPT管理",roleType = ApiServiceMapping.RoleType.RIGHT)
public class ChatGptService {

    @Autowired
    private ChatMapper chatMapper;
    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @ApiMapping(value = "insertOrUpdateChat", title = "创建chat聊天",type = ApiMapping.Type.POST)
    public void insertOrUpdateChat(Chat chat){
        chatMapper.insertOrUpdateChat(chat);
    }

    @Async
    public void insertChatMessage(ChatMessage chatMessage){
        chatMessageMapper.insert(chatMessage);
    }

    @Async
    public void insertSM(List<String> sm){
        chatMessageMapper.isms(sm);
    }

    @ApiMapping(value = "createChatMessages", title = "批量新增聊天内容",type = ApiMapping.Type.POST)
    public void insertChatMessage(List<Map> chatMessages){
        List<String> xl=new ArrayList<>();
        for(int i=0;i<chatMessages.size();i++){
            Map map=chatMessages.get(i);
            ChatMessage chatMessage=new ChatMessage().toMap(map);
            chatMessageMapper.insert(chatMessage);
            xl.add(chatMessage.getMessage());
        }
        this.insertSM(xl);
    }

    @ApiMapping(value = "updateChatMessages", title = "批量修改聊天内容",type = ApiMapping.Type.POST)
    public void updateChatMessages(List<Map> chatMessages){
        List<String> xl=new ArrayList<>();
        for(int i=0;i<chatMessages.size();i++){
            Map map=chatMessages.get(i);
            ChatMessage chatMessage=new ChatMessage().toMap(map);
            chatMessageMapper.updateById(chatMessage);
        }
    }

    @ApiMapping(value = "getChatByChatId", title = "获取聊天通过chatId")
    public Chat getChatByChatId(String chatId){
        return chatMapper.queryChatByChatId(chatId);
    }

    @ApiMapping(value = "getPublicChats", title = "获取公开聊天")
    public List<Chat> getPublicChats(){
        return chatMapper.queryPublicChatByChatId();
    }

    @ApiMapping(value = "getChatMessageByChatId", title = "获取聊天内容通过chatid")
    public List<ChatMessage> getChatMessageByChatId(String chatId){
        Map map=new HashMap();
        map.put("chat_id",chatId);
        return chatMessageMapper.selectByMap(map);
    }

    @ApiMapping(value = "getChatByUserId", title = "获取聊天通过userid")
    public List<Chat> getChatByUserId(String userId){
        List<Chat> chatList =  chatMapper.queryChat(userId);
        return chatList;
    }

    @ApiMapping(value = "deleteChatByChatId", title = "移除聊天")
    public void deleteChatByChatId(String chatId){
        chatMapper.deleteById(chatId);
        Map map=new HashMap();
        map.put("chat_id",chatId);
        chatMessageMapper.deleteByMap(map);
    }

    @ApiMapping(value = "deleteChatMessageByMessageId", title = "删除对话")
    public void deleteChatMessageByMessageId(String messageId){
        chatMessageMapper.deleteById(messageId);
    }

    @ApiMapping(value = "deleteChatMessageBatchByMessageIds", title = "批量删除对话")
    public void deleteChatMessageBatchByMessageIds(List<String> messageIds){
        chatMessageMapper.deleteBatchIds(messageIds);
    }


    @ApiMapping(value = "login", title = "登录openai",returnType=false)
    public ApiResponse login(String token) throws IOException {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder().build();
        Request request = new Request.Builder()
                .url("https://api.openai.com/dashboard/onboarding/login")
                .header("authorization", "Bearer "+token)
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        Response response = call.execute();
        int statusCode = response.code();
        if(statusCode==200){
            return ApiResponse.data(response.body().string());
        }else{
            return ApiResponse.error(statusCode,response.body().string());
        }
    }

    @ApiMapping(value = "apiKeys", title = "获取apiKeys",returnType=false)
    public ApiResponse apiKeys(String token) throws IOException {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder().build();
        Request request = new Request.Builder()
                .url("https://api.openai.com/dashboard/user/api_keys")
                .header("authorization", "Bearer "+token)
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        Response response = call.execute();
        // 获取状态码
        int statusCode = response.code();
        if(statusCode==200){
            return ApiResponse.data(response.body().string());
        }else{
            return ApiResponse.error(statusCode,response.body().string());
        }
    }

    @ApiMapping(value = "billing", title = "获取余额",returnType=false)
    public ApiResponse billing(String token) throws IOException {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder().build();
        Request request = new Request.Builder()
                .url("https://api.openai.com/dashboard/billing/credit_grants")
                .header("authorization", "Bearer "+token)
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        Response response = call.execute();
        // 获取状态码
        int statusCode = response.code();
        if(statusCode==200){
            return ApiResponse.data(response.body().string());
        }else{
            return ApiResponse.error(statusCode,response.body().string());
        }
    }

}
